/**
 * Copyright (c) 2015-2017, Henry Yang 杨勇 (gismail@foxmail.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lambkit.module.cms.rpc.model;

import java.util.Date;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.lambkit.common.service.ServiceKit;
import com.lambkit.common.util.DateTimeUtils;
import com.lambkit.common.util.StringUtils;
import com.lambkit.db.sql.column.Column;
import com.lambkit.module.cms.Cms;
import com.lambkit.module.cms.common.CmsConfig;
import com.lambkit.Lambkit;

import com.lambkit.module.cms.rpc.model.base.BaseCmsArticle;
import com.lambkit.module.cms.rpc.model.sql.CmsArticleCriteria;
import com.lambkit.module.cms.common.CmsConsts;
import com.lambkit.module.cms.common.util.JsoupUtils;
import com.lambkit.module.cms.common.util.MarkdownUtils;
import com.lambkit.module.cms.core.search.SearcherKit;
import com.lambkit.module.cms.rpc.api.CmsArticleService;
import com.lambkit.module.cms.rpc.service.impl.CmsArticleServiceImpl;
import com.lambkit.module.upms.rpc.model.UpmsUser;

/**
 * @author yangyong 
 * @website: www.lambkit.com
 * @email: gismail@foxmail.com
 * @date 2019-10-28
 * @version 1.0
 * @since 1.0
 */
public class CmsArticle extends BaseCmsArticle<CmsArticle> {

	private static final long serialVersionUID = 1L;
	
	/**
	 * 状态(1:通过)
	 */
	public static final int STATUS_NORMAL = 1;
	/**
	 * 状态(0未审核)
	 */
    public static final int STATUS_DRAFT = 0;
    /**
     * 状态(-1:不通过)
     */
    public static final int STATUS_TRASH = -1;
	
    
	public static CmsArticleService service() {
		return ServiceKit.inject(CmsArticleService.class, CmsArticleServiceImpl.class);
	}
	
	public static CmsArticleCriteria sql() {
		return new CmsArticleCriteria();
	}
	
	public static CmsArticleCriteria sql(Column column) {
		CmsArticleCriteria that = new CmsArticleCriteria();
		that.add(column);
        return that;
    }
	
	public CmsArticle() {
		CmsConfig config = Lambkit.config(CmsConfig.class);
		String dbconfig = config.getDbconfig();
		if(StrKit.notBlank(dbconfig)) {
			this.use(dbconfig);
		}
	}
	
	public boolean isNormal() {
        return STATUS_NORMAL==getStatus();
    }

    public boolean isDraft() {
        return STATUS_DRAFT==getStatus();
    }

    public boolean isTrash() {
        return STATUS_TRASH==getStatus();
    }
	
	public String getHtmlView() {
        return StrKit.isBlank(getStyle()) ? "article.html" : "article_" + getStyle().trim() + ".html";
    }

	public String getText() {
        return StringUtils.escapeHtml(JsoupUtils.getText(getContent()));
    }
	
    public String getContent() {
        String content = super.getContent();
        if (_isMarkdownMode()) {
            content = MarkdownUtils.toHtml(content);
            content = JsoupUtils.clean(content);
        }
        return content;
    }
	
	public boolean _isMarkdownMode() {
        return CmsConsts.EDIT_MODE_MARKDOWN.equals(getEditMode());
    }
	
	public String _getEditContent() {

        String originalContent = super.getContent();
        if (StringUtils.isBlank(originalContent) || _isMarkdownMode()) {
            return originalContent;
        }

        //ckeditor 编辑器有个bug，自动把 &lt; 转化为 < 和 把 &gt; 转化为 >
        //因此，此处需要 把 "&lt;" 替换为 "&amp;lt;" 和 把 "&gt;" 替换为 "&amp;gt;"
        //方案：http://komlenic.com/246/encoding-entities-to-work-with-ckeditor-3/
        return originalContent.replace("&lt;", "&amp;lt;")
                .replace("&gt;", "&amp;gt;");

    }

	public Date getCreated() {
		// TODO Auto-generated method stub
		return getCtime();
	}

	public String getHighlightContent() {
        return getStr("highlightContent");
    }

    public void setHighlightContent(String highlightContent) {
        put("highlightContent", highlightContent);
    }

    public String getHighlightTitle() {
        return getStr("highlightTitle");
    }

    public void setHighlightTitle(String highlightTitle) {
        put("highlightTitle", highlightTitle);
    }
    
    
    @Override
    public boolean save() {
    	// TODO Auto-generated method stub
    	boolean flag = super.save();
    	if(flag) {
    		SearcherKit.articleSearcher().addArticle(this);
    	}
    	return flag;
    }
    
    @Override
    public boolean update() {
    	// TODO Auto-generated method stub
    	boolean flag = super.update();
    	if(flag) {
    		SearcherKit.articleSearcher().updateArticle(this);
    	}
    	return flag;
    }
    
    @Override
    public boolean delete() {
    	// TODO Auto-generated method stub
    	Long id = this.getArticleId();
    	boolean flag = super.delete();
    	if(flag) {
    		SearcherKit.articleSearcher().deleteArticle(id);
    	}
    	return flag;
    }
    
    /**
     * 用户名（账号）
     * @return
     */
    public java.lang.String getUsername() {
		return this.get("username");
	}
    
    public java.lang.String getRealname() {
		return this.get("realname");
	}
    
    public java.lang.String getEmail() {
		return this.get("email");
	}
    public java.lang.Integer getSex() {
		return this.get("sex");
	}
    
    /**
     * 用户头像
     * @return
     */
    public String getAvatar() {
    	return this.get("avatar");
    }
    
    /**
     * 评论数量
     * @return
     */
    public Long getCommentNum() {
    	return this.get("comment_num");
    }
    
    /**
     * 分类名称
     * @return
     */
    public String getCategory() {
    	return this.get("category");
    }
    
    public void joinUser() {
    	UpmsUser user = UpmsUser.service().findById(this.getUserId());
    	if(user!=null) {
    		Long tm = user.getCtime();
    		if(tm!=null) {
    			this.put("utime", DateTimeUtils.longToDate(tm));
    		}
        	user.remove("ctime", "password", "salt");
        	this.put(user);
    	}
    }
    
    public void joinForView() {
    	//String sql = "select count(*) from cms_comment where reftype=0 and refid=?";
    	//Long cnt = Cms.db().queryLong(sql, this.getArticleId());
    	//this.put("comment_num", cnt);
    	StringBuilder sb = new StringBuilder();
    	sb.append("SELECT c.name as category, count(t.refid) as comment_num ");
    	sb.append("FROM cms_article_category ac ");
    	sb.append("LEFT JOIN cms_category c on ac.category_id=c.category_id ");
    	sb.append("LEFT JOIN cms_comment t on t.reftype=0 and t.refid=ac.article_id ");
    	sb.append("where ac.article_id=?");
    	Record r = Cms.db().findFirst(sb.toString(), this.getArticleId());
    	this.put(r);
    }
    
}
